package com.framework.web.bus.service;

import com.framework.web.bus.domain.UserAddress;
import com.framework.web.bus.repository.UserAddressRepository;
import com.framework.web.common.domain.BusinessConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author zqtao
 * @version V1.0
 * @Title: Service
 * @Description: 业务层
 * @date 2016-09-11
 */
@Service
public class UserAddressService {

    @Autowired
    private UserAddressRepository userAddressRepository;

    /**
     * 新增或者保存
     *
     * @param userAddress
     * @return
     */
    public UserAddress save(UserAddress userAddress) {
        return userAddressRepository.save(userAddress);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(String id) {
        userAddressRepository.delete(id);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public UserAddress findById(String id) {
        return userAddressRepository.findOne(id);
    }

    /**
     * 根据用户ID获取有效的地址列表
     *
     * @param userId
     * @return
     */
    public List<UserAddress> findByUserId(String userId) {
        return userAddressRepository.findByUserIdAndStatus(userId, BusinessConstants.STATUS.NORMAL);
    }

    @Transactional
    public void saveUserAddress(UserAddress userAddress) {
        //判断是否默认地址
       if(userAddress.equals(BusinessConstants.DEFAULTS_ADDRESS.YES)) {
          List<UserAddress> userAddressList = userAddressRepository.findByUserIdAndStatus(userAddress.getUserId(), BusinessConstants.STATUS.NORMAL);
          for(UserAddress ua :userAddressList) {
                ua.setDefaultsAddress(BusinessConstants.DEFAULTS_ADDRESS.NO);
              this.save(ua);
          }
       }
       this.save(userAddress);
    }

}
